<?php

class Order extends CI_Controller {

    function __construct() {
        parent::__construct();
        $this->load->model("base_model");
        $this->load->model("order_model");
        $this->load->model("custom_model");
        $this->load->model("car_model");
        $this->load->model("custom_address_model");
        $this->load->model("province_model");
        $this->load->model("city_model");
        $this->load->model("district_model");
        $this->load->model("admin_user_model");
        $this->load->model("admin_role_model");
        $this->load->model("driver_model");
        $this->load->model("order_fee_model");
        $this->load->model("order_genjin_model");
        $this->load->model("order_genzong_model");

        $this->load->service("admin_manage_service");
        $this->check = $this->admin_manage_service;
        $this->_adminInfo = $this->check->checkAdminLogin();
        #

        $this->projectSet = [
            "url" => [
                "add" => MANAGE_URL . "&c=order&m=add",
                "doAdd" => MANAGE_URL . "&c=order&m=doAdd",
                "edit" => MANAGE_URL . "&c=order&m=edit",
                "doEdit" => MANAGE_URL . "&c=order&m=doEdit",
                "list" => MANAGE_URL . "&c=order&m=lists",
                "doDel" => MANAGE_URL . "&c=order&m=doDel",
                "doSelectIds" => MANAGE_URL . "&c=order&m=doSelectIds",
                "batchAddPaiche" => MANAGE_URL . "&c=order&m=batchAddPaiche",
                "doBatchAddPaiche" => MANAGE_URL . "&c=order&m=doBatchAddPaiche",
                "doBatchCancelPaiche" => MANAGE_URL . "&c=order&m=doBatchCancelPaiche",
                "addSecondOrder" => MANAGE_URL . "&c=order&m=addSecondOrder",
                "doAddSecondOrder" => MANAGE_URL . "&c=order&m=doAddSecondOrder",
                "viewOrderFee" => MANAGE_URL . "&c=orderFee&m=view",
                "getCustomAddress" => MANAGE_URL . "&c=customAddress&m=getCustomAddress",
                "getProvince" => MANAGE_URL . "&c=province&m=getProvince",
                "getCity" => MANAGE_URL . "&c=city&m=getCity",
                "getDistrict" => MANAGE_URL . "&c=district&m=getDistrict",
                "getCar" => MANAGE_URL . "&c=car&m=getCar",
            ],
            "file" => [
                "view" => "admin/order",
                "js" => "admin/js/order",
                "cache_ids_name" => "cache_order_ids",
                "power_name" => "order"
            ],
        ];
    }

    /*
     * 添加
     */

    function add() {

        try {
            $this->check->checkPower(array("power" => $this->projectSet["file"]["power_name"] . "_add"));

            $data["navName"] = "添加";

            $data["type"] = $this->order_model->type();
            $data["kehu"] = $this->custom_model->getData("where type_id=2 and status_id=1", 1, 0);

            #订单号
            $today = date("Ymd");
            $order = $this->order_model->getData("where set_day=" . $today . " order by set_id desc", 1, 1, "");
            if (!empty($order)) {
                $set_id = $order[0]["set_id"] + 1;
            } else {
                $set_id = 1;
            }
            $data["set_day"] = $today;
            $data["set_id"] = $set_id;

            $order_no = "KS" . $today . str_pad($set_id, 3, 0, STR_PAD_LEFT);
            $data["order_no"] = $order_no;

            #提货地



            $data["doAddUrl"] = $this->projectSet["url"]["doAdd"];

            $this->layout->view($this->projectSet["file"]["view"] . '/add', $data);
        } catch (Exception $e) {
            show_error($msg = $e->getMessage(), $e->getCode() ? $e->getCode() : 200, "系统提示");
        }
    }

    /*
     * 编辑
     */

    function edit() {

        try {

            #权限
            $this->check->checkPower(array("power" => $this->projectSet["file"]["power_name"] . "_view"));

            $data["navName"] = "编辑";

            $id = $this->input->getInt("id", TRUE);
            $editData = $this->order_model->getDataById($id);
            if (empty($editData)) {
                throw new Exception("没有此数据");
            }

            $data["type"] = $this->order_model->type();
            $data["kehu"] = $this->custom_model->getData("where type_id=2 and status_id=1", 1, 0);

            $data["editData"] = $editData;

            $data["doAddUrl"] = $this->projectSet["url"]["doEdit"];

            $this->layout->view($this->projectSet["file"]["view"] . '/add', $data);
        } catch (Exception $e) {
            show_error($msg = $e->getMessage(), $e->getCode() ? $e->getCode() : 200, "系统提示");
        }
    }

    /*
     * 列表
     */

    function lists() {

        try {

            #权限
            $this->check->checkPower(array("power" => $this->projectSet["file"]["power_name"] . "_view"));

            $data["navName"] = "订单列表";

            $page = $this->input->getInt("page", TRUE);
            if ($page <= 0) {
                $page = 1;
            }
            $pageCount = $this->input->getInt("limit", TRUE);
            if ($pageCount <= 0) {
                $pageCount = 50;
            }
            if ($pageCount >= 200) {
                $pageCount = 200;
            }
            $data["page"] = $page;
            $data["pageCount"] = $pageCount;

            $first = $this->input->getInt("first", true);
            if ($first == 1) {
                $this->session->unset_userdata([$this->projectSet["file"]["cache_ids_name"]]);
            }

            $searchParam = $this->_searchParam();
            $where = $searchParam["where"];
            $pageStrArr = $searchParam["pageStrArr"];
            foreach ($searchParam["data"] as $k => $v) {
                ${$k} = $v;
                $data[$k] = $v;
            }

            $type = $this->order_model->type();
            $data["type"] = $type;

            $secondType = $this->order_model->secondType();
            $data["secondType"] = $secondType;

            $status = $this->order_model->status();
            $data["status"] = $status;

            $completeStatus = $this->order_model->completeStatus();
            $data["completeStatus"] = $completeStatus;

            $isHuicheng = $this->order_model->isHuicheng();
            $data["isHuicheng"] = $isHuicheng;
            
            //echo $where;

            //var_dump($isHuicheng);

            $carType = $this->car_model->carType();

            $data["kehu"] = $this->custom_model->getData("where type_id=2 and status_id=1", 1, 0);
            $data["diaodu"] = $this->base_model->getData("select au.* from " . $this->admin_user_model->tableName . " au left join " . $this->admin_role_model->tableName . " ar on au.role_id=ar.id where ar.type_id=1 and au.status_id=1", 1, 0, " order by au.id desc");
            $data["car"] = $this->car_model->getData("where status_id=1", 1, 0);
            $data["gongyingshang"] = $this->custom_model->getData("where type_id=1 and status_id=1", 1, 0);

            $province = $this->province_model->getDataSetKey();
            //$city = $this->city_model->getDataSetKey();
            //$district = $this->district_model->getDataSetKey();

            $sql = " from " . $this->order_model->tableName . " o";
            $sql .= " left join " . $this->car_model->tableName . " c on o.car_id=c.id";
            $sql .= " left join " . $this->custom_model->tableName . " ct on o.kehu_custom_id=ct.id";
            $sql .= " left join " . $this->admin_user_model->tableName . " diaodu on o.diaodu_user_id=diaodu.id";
            $sql .= " left join " . $this->admin_user_model->tableName . " cwjl on o.cwjl_user_id=cwjl.id";
            $sql .= " left join " . $this->driver_model->tableName . " zhujia on o.zhujia_driver_id=zhujia.id";
            $sql .= " left join " . $this->driver_model->tableName . " fujia on o.fujia_driver_id=fujia.id";

            $listNum = $this->base_model->getDataCount("select o.id" . $sql . " " . $where);

            $is_ajax = $this->input->is_ajax_request();
            if ($is_ajax) {
                
                //echo $where;


                $dataList = $this->base_model->getData("select o.*,ct.cmp_bf as ct_cmp_bf,diaodu.truename as diaodu_truename,cwjl.truename as cwjl_truename,c.car_number as c_car_number,c.car_type as c_car_type,zhujia.driver_name as zhujia_driver_name,zhujia.tel as zhujia_tel,fujia.driver_name as fujia_driver_name,fujia.tel as fujia_tel" . $sql . " " . $where, $page, $pageCount);

                foreach ($dataList as $k => $v) {
                    $dataList[$k]["created_at_alias"] = date("Y-m-d H:i:s", $v["created_at"]);
                    $dataList[$k]["updated_at_alias"] = date("Y-m-d H:i:s", $v["updated_at"]);
                    $dataList[$k]["type_name"] = $type[$v["type_id"]]["name"];
                    $dataList[$k]["type_name"] .= $v["second_type_id"] > 0 ? "-" . $secondType[$v["second_type_id"]]["name"] : "";
                    $dataList[$k]["status_name"] = $status[$v["status_id"]]["name"];
                    $dataList[$k]["order_date_alias"] = date("Y-m-d", $v["order_date"]);

                    $org_province = !empty($province[$v["org_province_id"]]) ? $province[$v["org_province_id"]]["name"] : "";
                    //$org_city = !empty($city[$v["org_city_id"]]) ? $city[$v["org_city_id"]]["name"] : "";
                    //$org_district = !empty($district[$v["org_district_id"]]) ? $province[$v["org_district_id"]]["name"] : "";
                    //$dataList[$k]["org_tag"] = $org_province . "/" . $org_city . "/" . $v["org_address"];
                    $dataList[$k]["org_tag"] = $org_province . "/" . $v["org_address"];

                    $dest_province = !empty($province[$v["dest_province_id"]]) ? $province[$v["dest_province_id"]]["name"] : "";
                    //$dest_city = !empty($city[$v["dest_city_id"]]) ? $city[$v["dest_city_id"]]["name"] : "";
                    //$dest_district = !empty($district[$v["dest_district_id"]]) ? $district[$v["dest_district_id"]]["name"] : "";
                    //$dataList[$k]["dest_tag"] = $dest_province . "/" . $dest_city . "/" . $v["dest_address"];
                    $dataList[$k]["dest_tag"] = $dest_province . "/" . $v["dest_address"];

                    $dataList[$k]["c_car_type_name"] = !empty($carType[$v["c_car_type"]]) ? $carType[$v["c_car_type"]]["name"] : "";
                    $dataList[$k]["xianghao_tag"] = $v["xianghao"] . ($v["xianghao2"] ? "," . $v["xianghao2"] : "");
                    $dataList[$k]["is_huicheng_name"] = $v["is_huicheng"] ? "已安排" : "未安排";
                }
                $data["dataList"] = $dataList;

                $result = [
                    "code" => 0,
                    "count" => $listNum,
                    "data" => $dataList,
                    "msg" => ""
                ];
                echo jsonEncode($result);
                exit;
            }

            #进行分页
            $pageStr = "";
            if (!empty($pageStrArr)) {
                foreach ($pageStrArr as $k => $v) {
                    $pageStr .= "&" . $k . "=" . $v;
                }
            }
            $data['base_url'] = $this->projectSet["url"]["list"] . $pageStr;

            $data["listNum"] = $listNum;
            $data["pageStr"] = $pageStr;

            $this->layout->view($this->projectSet["file"]["view"] . '/list', $data);
        } catch (Exception $e) {
            show_error($msg = $e->getMessage(), $e->getCode() ? $e->getCode() : 200, "系统提示");
        }
    }

    /*
     * 
     */

    function doAdd() {

        #权限

        $flag = 0;
        $msg = "操作失败";

        try {

            $this->check->checkPower(array("power" => $this->projectSet["file"]["power_name"] . "_add"));

            $needField = $this->order_model->needField();
            $fieldValue = $this->common->checkField($needField);

            $fieldValue["order_date"] = strtotime($fieldValue["order_date"]);

            $this->db->trans_start();

            if ($fieldValue["org_id"] == -1) {
                if ($fieldValue["org_province_id"] <= 0) {
                    throw new Exception("请选择提货地州");
                }
                if ($fieldValue["org_city_id"] <= 0) {
                    //throw new Exception("请选择提货地城市");
                }
                if ($fieldValue["org_address"] == "") {
                    //throw new Exception("请填上提货地具体地址");
                }
                $fieldValue["org_id"] = $this->custom_address_model->addData([
                    "custom_id" => $fieldValue["kehu_custom_id"],
                    "type_id" => 1,
                    "province_id" => $fieldValue["org_province_id"],
                    "city_id" => $fieldValue["org_city_id"],
                    "district_id" => $fieldValue["org_district_id"],
                    "address" => $fieldValue["org_address"],
                ]);
            } else {
                if ($fieldValue["org_id"] <= 0) {
                    throw new Exception("请选择提货地");
                }
                $org = $this->custom_address_model->getDataById($fieldValue["org_id"]);
                if (empty($org)) {
                    throw new Exception("选择的提货地不存在");
                }
                $fieldValue["org_province_id"] = $org["province_id"];
                $fieldValue["org_city_id"] = $org["city_id"];
                $fieldValue["org_district_id"] = $org["district_id"];
                $fieldValue["org_address"] = $org["address"];
            }

            if ($fieldValue["dest_id"] == -1) {
                if ($fieldValue["dest_province_id"] <= 0) {
                    throw new Exception("请选择送货地州");
                }
                if ($fieldValue["dest_city_id"] <= 0) {
                    //throw new Exception("请选择送货地城市");
                }
                if ($fieldValue["dest_address"] == "") {
                    //throw new Exception("请填上送货地具体地址");
                }
                $fieldValue["dest_id"] = $this->custom_address_model->addData([
                    "custom_id" => $fieldValue["kehu_custom_id"],
                    "type_id" => 2,
                    "province_id" => $fieldValue["dest_province_id"],
                    "city_id" => $fieldValue["dest_city_id"],
                    "district_id" => $fieldValue["dest_district_id"],
                    "address" => $fieldValue["dest_address"],
                ]);
            } else {
                if ($fieldValue["dest_id"] <= 0) {
                    throw new Exception("请选择送货地");
                }
                $dest = $this->custom_address_model->getDataById($fieldValue["dest_id"]);
                if (empty($dest)) {
                    throw new Exception("选择的送货地不存在");
                }
                $fieldValue["dest_province_id"] = $dest["province_id"];
                $fieldValue["dest_city_id"] = $dest["city_id"];
                $fieldValue["dest_district_id"] = $dest["district_id"];
                $fieldValue["dest_address"] = $dest["address"];
            }

            if ($fieldValue["xianghao"] != "") {
                if (!validateContainerNumber($fieldValue["xianghao"])) {
                    //throw new Exception("箱号1号码有误");
                }
            }
            if ($fieldValue["xianghao2"] != "") {
                if (!validateContainerNumber($fieldValue["xianghao2"])) {
                    //throw new Exception("箱号2号码有误");
                }
            }

            $uData = array_merge($fieldValue, [
                "status_id" => "created",
                "created_user_id" => $this->_adminInfo["id"],
                "created_at" => time(),
                "updated_at" => time(),
            ]);
            $insert_id = $this->order_model->addData($uData);

            $this->order_model->updateData([
                "fieldArr" => [
                    "same_order_id" => $insert_id,
                    "updated_at" => time(),
                ],
                "whereArr" => [
                    "id" => $insert_id,
                ],
            ]);

            $flag = 1;
            $msg = "操作成功";

            $this->db->trans_complete();
        } catch (Exception $e) {
            $msg = $e->getMessage();
        }

        $outArr = array("flag" => $flag, "msg" => $msg);
        echo jsonEncode($outArr);
    }

    /*
     * 
     */

    function doEdit() {

        $flag = 0;
        $msg = "操作失败";

        try {

            $this->check->checkPower(array("power" => $this->projectSet["file"]["power_name"] . "_edit",));

            $needField = $this->order_model->needField();

            $fieldValue = $this->common->checkField($needField);

            $id = $this->input->postInt("id", TRUE);

            $oldData = $this->order_model->getDataById($id);
            if (empty($oldData)) {
                throw new Exception("数据不存在");
            }
            $orderFee = $this->order_fee_model->getData("where order_id=" . $id . " and pay_status=1", 1, 0, "");
            if (!empty($orderFee)) {
                //throw new Exception("该订单已有收付款记录，不可操作");
            }

            $fieldValue["order_date"] = strtotime($fieldValue["order_date"]);

            $this->db->trans_start();

            if ($fieldValue["org_id"] == -1) {
                if ($fieldValue["org_province_id"] <= 0) {
                    throw new Exception("请选择提货地州");
                }
                if ($fieldValue["org_city_id"] <= 0) {
                    //throw new Exception("请选择提货地城市");
                }
                if ($fieldValue["org_address"] == "") {
                    //throw new Exception("请填上提货地具体地址");
                }
                //$oldOrg=$oldData["org_province_id"].$oldData["org_province_id"].$oldData["org_province_id"].$oldData["org_province_id"];
                $fieldValue["org_id"] = $this->custom_address_model->addData([
                    "custom_id" => $fieldValue["kehu_custom_id"],
                    "type_id" => 1,
                    "province_id" => $fieldValue["org_province_id"],
                    "city_id" => $fieldValue["org_city_id"],
                    "district_id" => $fieldValue["org_district_id"],
                    "address" => $fieldValue["org_address"],
                ]);
            } else {
                if ($fieldValue["org_id"] <= 0) {
                    throw new Exception("请选择提货地");
                }
                $org = $this->custom_address_model->getDataById($fieldValue["org_id"]);
                if (empty($org)) {
                    throw new Exception("选择的提货地不存在");
                }
                $fieldValue["org_province_id"] = $org["province_id"];
                $fieldValue["org_city_id"] = $org["city_id"];
                $fieldValue["org_district_id"] = $org["district_id"];
                $fieldValue["org_address"] = $org["address"];
            }

            if ($fieldValue["dest_id"] == -1) {
                if ($fieldValue["dest_province_id"] <= 0) {
                    throw new Exception("请选择送货地州");
                }
                if ($fieldValue["dest_city_id"] <= 0) {
                    //throw new Exception("请选择送货地城市");
                }
                if ($fieldValue["dest_address"] == "") {
                    //throw new Exception("请填上送货地具体地址");
                }
                $fieldValue["dest_id"] = $this->custom_address_model->addData([
                    "custom_id" => $fieldValue["kehu_custom_id"],
                    "type_id" => 2,
                    "province_id" => $fieldValue["dest_province_id"],
                    "city_id" => $fieldValue["dest_city_id"],
                    "district_id" => $fieldValue["dest_district_id"],
                    "address" => $fieldValue["dest_address"],
                ]);
            } else {
                if ($fieldValue["dest_id"] <= 0) {
                    throw new Exception("请选择送货地");
                }
                $dest = $this->custom_address_model->getDataById($fieldValue["dest_id"]);
                if (empty($dest)) {
                    throw new Exception("选择的送货地不存在");
                }
                $fieldValue["dest_province_id"] = $dest["province_id"];
                $fieldValue["dest_city_id"] = $dest["city_id"];
                $fieldValue["dest_district_id"] = $dest["district_id"];
                $fieldValue["dest_address"] = $dest["address"];
            }

            if ($fieldValue["xianghao"] != "") {
                if (!validateContainerNumber($fieldValue["xianghao"])) {
                    //throw new Exception("箱号1号码有误");
                }
            }
            if ($fieldValue["xianghao2"] != "") {
                if (!validateContainerNumber($fieldValue["xianghao2"])) {
                    //throw new Exception("箱号2号码有误");
                }
            }

            unset($fieldValue["order_no"]);
            unset($fieldValue["set_day"]);
            unset($fieldValue["set_id"]);

            $uData = array_merge($fieldValue, [
                "updated_at" => time(),
            ]);

            $data = [
                "fieldArr" => $uData,
                "whereArr" => [
                    "id" => $id,
                ],
            ];
            $this->order_model->updateData($data);

            $this->order_model->updateData([
                "fieldArr" => [
                    "type_id" => $fieldValue["type_id"],
                    "kehu_custom_id" => $fieldValue["kehu_custom_id"],
                    "goods_name" => $fieldValue["goods_name"],
                    "num" => $fieldValue["num"],
                    "weight" => $fieldValue["weight"],
                    "xianghao" => $fieldValue["xianghao"],
                    "xianghao2" => $fieldValue["xianghao2"],
                ],
                "whereArr" => [
                    "same_order_id" => $oldData["same_order_id"],
                ],
            ]);

            $flag = 1;
            $msg = "操作成功";

            $this->db->trans_complete();
        } catch (Exception $e) {
            $msg = $e->getMessage();
        }

        $outArr = array("flag" => $flag, "msg" => $msg);
        echo jsonEncode($outArr);
    }

    /*
     * 删除记录
     */

    public function doDel() {

        $flag = 0;
        $msg = "操作失败";

        try {

            $this->check->checkPower(array("power" => $this->projectSet["file"]["power_name"] . "_del"));

            $where = "";
            $is_sql = $this->input->getInt("is_sql", true);
            if ($is_sql == 1) {
                $searchParam = $this->_searchParam();
                $where = $searchParam["where"];
            } else {
                $cache_id_arr = $this->session->userdata($this->projectSet["file"]["cache_ids_name"]);
                if (empty($cache_id_arr)) {
                    throw new Exception("没有选择订单");
                }
                $ids = join(",", $cache_id_arr);
                $where = "where id in (" . $ids . ")";
            }
            $batchData = $this->order_model->getData($where, 1, 0, "");
            if (empty($batchData)) {
                throw new Exception("不存在订单");
            }
            if (count($batchData) > 1) {
                throw new Exception("一次只能删除一个订单");
            }
            $oldData = $batchData[0];
            $order_id = $oldData["id"];

            $id_arr = array_column($batchData, "id");
            $ids = join(",", $id_arr);

            foreach ($batchData as $k => $v) {
                $orderFee = $this->order_fee_model->getData("where order_id=" . $v["id"], 1, 1, "");
                if (!empty($orderFee)) {
                    throw new Exception("订单【" . $v["order_no"] . "】已存在收支费用，不可删除");
                }
                //如果是主单，且下面还有二次运输不可删除
                if ($v["second_order_id"] == 0) {
                    $exist = $this->order_model->getData("where second_order_id=" . $v["id"], 1, 1, "");
                    if (!empty($exist)) {
                        throw new Exception("订单【" . $v["order_no"] . "】存在二次运输，请删除二次运输后，再删此主单");
                    }
                }
            }

            $this->db->trans_start();

            $paramArr = array(
                "whereArr" => "id in(" . $ids . ")",
            );
            $result = $this->order_model->delData($paramArr);

            $this->order_genjin_model->delData([
                "whereArr" => "order_id in(" . $ids . ")",
            ]);
            $this->order_genzong_model->delData([
                "whereArr" => "order_id in(" . $ids . ")",
            ]);

            //旧的车辆
            $exsit = $this->order_model->getData("where id<" . $order_id . " and car_id=" . $oldData["car_id"], 1, 1);
            if (!empty($exsit)) {
                //print_r($exsit);
                $this->order_model->updateData([
                    "fieldArr" => [
                        "is_huicheng" => 0,
                        "updated_at" => time(),
                    ],
                    "whereArr" => [
                        "id" => $exsit[0]["id"],
                    ],
                ]);
            }

            $flag = 1;
            $msg = "操作成功";

            $this->db->trans_complete();
        } catch (Exception $e) {
            $msg = $e->getMessage();
        }
        $outArr = array("flag" => $flag, "msg" => $msg);
        echo jsonEncode($outArr);
    }

    public function _searchParam() {

        $pageStrArr = array();

        if ($this->_adminInfo["role"]["type_id"] == 1) {
            $where = "where (o.status_id='created' or (o.status_id!='created' and o.diaodu_user_id=" . $this->_adminInfo["id"] . "))";
        } else {
            $where = "where 1";
        }

        $status_id = $this->input->getPostStr("status_id", TRUE);
        if ($status_id != "") {
            $pageStrArr["status_id"] = $status_id;
            $where .= " AND o.status_id = '" . $status_id . "'";
        }
        $data["status_id"] = $status_id;
        //状态
        $type_id = $this->input->getPostInt("type_id", TRUE);
        if ($type_id > 0) {
            $pageStrArr["type_id"] = $type_id;
            $where .= " AND o.type_id = " . $type_id;
        }
        $data["type_id"] = $type_id;

        $second_type_id = $this->input->getPostInt("second_type_id", TRUE);
        if ($second_type_id > 0) {
            $pageStrArr["second_type_id"] = $second_type_id;
            $where .= " AND o.second_type_id = " . $second_type_id;
        }
        $data["second_type_id"] = $second_type_id;

        $car_id = $this->input->getPostInt("car_id", TRUE);
        if ($car_id > 0) {
            $pageStrArr["car_id"] = $car_id;
            $where .= " AND o.car_id = " . $car_id;
        }
        $data["car_id"] = $car_id;

        $order_date_range = $this->input->getPostStr("order_date_range", TRUE);
        if ($order_date_range === null) {
            $order_date_range = date("Y-m-d", strtotime("-29 days")) . " - " . date("Y-m-d");
        }
        //var_dump($order_date_range);
        
        if ($order_date_range != "") {
            $order_date_range_arr = explode(" - ", $order_date_range);
            $order_date_start = strtotime($order_date_range_arr[0]);
            $where .= " AND o.order_date >=" . $order_date_start;
            $order_date_end = strtotime($order_date_range_arr[1]) + 3600 * 24;
            $where .= " AND o.order_date <" . $order_date_end;
        }
        //var_dump($order_date_range);
        $pageStrArr["order_date_range"] = $order_date_range;
        $data["order_date_range"] = $order_date_range;

        $order_no = $this->input->getPostStr("order_no", TRUE);
        if ($order_no != "") {
            $pageStrArr["order_no"] = $order_no;
            $where .= " AND o.order_no like '%" . $order_no . "%'";
        }
        $data["order_no"] = $order_no;

        $is_huicheng = $this->input->getPostStr("is_huicheng", TRUE);
        if ($is_huicheng !== null && $is_huicheng !== "") {
            $pageStrArr["is_huicheng"] = $is_huicheng;
            $where .= " AND is_huicheng = " . $is_huicheng;
        }
        $data["is_huicheng"] = $is_huicheng;
        //var_dump($is_huicheng);

        $kehu_custom_id = $this->input->getPostInt("kehu_custom_id", TRUE);
        if ($kehu_custom_id > 0) {
            $pageStrArr["kehu_custom_id"] = $kehu_custom_id;
            $where .= " AND o.kehu_custom_id = " . $kehu_custom_id;
        }
        $data["kehu_custom_id"] = $kehu_custom_id;

        $diaodu_user_id = $this->input->getPostInt("diaodu_user_id", TRUE);
        if ($diaodu_user_id > 0) {
            $pageStrArr["diaodu_user_id"] = $diaodu_user_id;
            $where .= " AND o.diaodu_user_id = " . $diaodu_user_id;
        }
        $data["diaodu_user_id"] = $diaodu_user_id;

        $complete_status = $this->input->getPostInt("complete_status", TRUE);
        if ($complete_status > 0) {
            if ($complete_status == 1) {
                $where .= " AND o.status_id = 'completed'";
            } else if ($complete_status == 2) {
                $where .= " AND o.status_id not in('completed')";
            } else if ($complete_status == 3) {
                $where .= " AND o.status_id ='created'";
            }
            $pageStrArr["complete_status"] = $complete_status;
        }

        $data["complete_status"] = $complete_status;

        $gongyingshang_custom_id = $this->input->getPostInt("gongyingshang_custom_id", TRUE);
        if ($gongyingshang_custom_id > 0) {
            $pageStrArr["gongyingshang_custom_id"] = $gongyingshang_custom_id;
            $where .= " AND o.gongyingshang_custom_id = " . $gongyingshang_custom_id;
        }
        $data["gongyingshang_custom_id"] = $gongyingshang_custom_id;

        return [
            "data" => $data,
            "pageStrArr" => $pageStrArr,
            "where" => $where,
        ];
    }

    public function doSelectIds() {

        #权限
        //$this->check->checkPower(array("power" => "idcard_edit", "ajax" => 1));

        $flag = 0;
        $msg = "操作失败";
        $id_arr = $this->input->postStr("ids", TRUE, false);

        try {
            $sessionData = [
                $this->projectSet["file"]["cache_ids_name"] => $id_arr,
            ];
            $this->session->set_userdata($sessionData);

            $flag = 1;
            $msg = "操作成功";
            //事务结束
        } catch (Exception $e) {
            $msg = $e->getMessage();
        }
        $outArr = array("flag" => $flag, "msg" => $msg);
        echo jsonEncode($outArr);
    }

    /*
     * 派车作业
     */

    function batchAddPaiche() {

        try {

            $this->check->checkPower(array("power" => $this->projectSet["file"]["power_name"] . "_paiche", "ajax" => 1));

            $data = [];

            $where = "";
            $is_sql = $this->input->getInt("is_sql", true);
            if ($is_sql == 1) {
                $searchParam = $this->_searchParam();
                $where = $searchParam["where"];
            } else {
                $cache_id_arr = $this->session->userdata($this->projectSet["file"]["cache_ids_name"]);
                if (empty($cache_id_arr)) {
                    throw new Exception("没有选择订单");
                }
                $ids = join(",", $cache_id_arr);
                $where = "where id in (" . $ids . ")";
            }

            $order = $this->order_model->getData($where, 1, 0, "");
            if (empty($order)) {
                throw new Exception("不存在订单");
            }
            if (count($order) > 1) {
                throw new Exception("一次只能派车一个订单");
            }
            $editData = $this->order_model->getDataById($order[0]["id"]);
            $data["editData"] = $editData;

            $data["gongyingshang"] = $this->custom_model->getData("where type_id=1 and status_id=1", 1, 0);

            $data["doAddUrl"] = $this->projectSet["url"]["doBatchAddPaiche"];

            $this->layout->view($this->projectSet["file"]["view"] . '/batchAddPaiche', $data);
        } catch (Exception $e) {
            $msg = $e->getMessage();
            show_error($msg, 200, "系统提示");
        }
    }

    /*
     * 
     */

    function doBatchAddPaiche() {

        $flag = 0;
        $msg = "操作失败";

        try {
            $this->check->checkPower(array("power" => $this->projectSet["file"]["power_name"] . "_paiche", "ajax" => 1));

            $needField = $this->order_model->paicheNeedField();
            $fieldValue = $this->common->checkField($needField);

            $fieldValue["pending_vehicle_at"] = strtotime($fieldValue["pending_vehicle_at"]);

            $where = "";
            $is_sql = $this->input->getInt("is_sql", true);
            if ($is_sql == 1) {
                $searchParam = $this->_searchParam();
                $where = $searchParam["where"];
            } else {
                $cache_id_arr = $this->session->userdata($this->projectSet["file"]["cache_ids_name"]);
                if (empty($cache_id_arr)) {
                    throw new Exception("没有选择订单");
                }
                $ids = join(",", $cache_id_arr);
                $where = "where id in (" . $ids . ")";
            }
            $dataS = $this->order_model->getData($where, 1, 0, "");
            if (empty($dataS)) {
                throw new Exception("不存在订单");
            }
            if (count($dataS) > 1) {
                throw new Exception("一次只能派车一个订单");
            }

            $oldData = $dataS[0];

            if ($oldData["status_id"] != "created" && $oldData["status_id"] != "pending_vehicle") {
                throw new Exception("只有订单车辆还未发车时，才可修改派车");
            }

            $order_id = $oldData["id"];

            $car = $this->car_model->getDataById($fieldValue["car_id"]);
            if (empty($car)) {
                throw new Exception("没有此车辆");
            }

            $this->db->trans_start();

            $uData = array_merge($fieldValue, [
                "diaodu_user_id" => $car["diaodu_user_id"],
                "cwjl_user_id" => $car["cwjl_user_id"],
                "zhujia_driver_id" => $car["zhujia_driver_id"],
                "fujia_driver_id" => $car["fujia_driver_id"],
                "status_id" => $oldData["status_id"] == "created" ? "pending_vehicle" : $oldData["status_id"],
                "updated_at" => time(),
            ]);
            $data = [
                "fieldArr" => $uData,
                "whereArr" => [
                    "id" => $order_id,
                ],
            ];
            $this->order_model->updateData($data);

            if ($oldData["car_id"] == 0) {
                $exsit = $this->order_model->getData("where id<" . $order_id . " and car_id=" . $fieldValue["car_id"], 1, 1);
                if (!empty($exsit)) {
                    $this->order_model->updateData([
                        "fieldArr" => [
                            "is_huicheng" => 1,
                            "updated_at" => time(),
                        ],
                        "whereArr" => [
                            "id" => $exsit[0]["id"],
                        ],
                    ]);
                }
            } else {
                if ($oldData["car_id"] != $fieldValue["car_id"]) {
                    //新的车辆
                    $exsit = $this->order_model->getData("where id<" . $order_id . " and car_id=" . $fieldValue["car_id"], 1, 1);
                    if (!empty($exsit)) {
                        $this->order_model->updateData([
                            "fieldArr" => [
                                "is_huicheng" => 1,
                                "updated_at" => time(),
                            ],
                            "whereArr" => [
                                "id" => $exsit[0]["id"],
                            ],
                        ]);
                    }
                    //旧的车辆
                    $exsit = $this->order_model->getData("where id<" . $order_id . " and car_id=" . $oldData["car_id"], 1, 1);
                    if (!empty($exsit)) {
                        //print_r($exsit);
                        $this->order_model->updateData([
                            "fieldArr" => [
                                "is_huicheng" => 0,
                                "updated_at" => time(),
                            ],
                            "whereArr" => [
                                "id" => $exsit[0]["id"],
                            ],
                        ]);
                    }
                }
            }



            $this->db->trans_complete();

            $flag = 1;
            $msg = "操作成功";
        } catch (Exception $e) {
            $msg = $e->getMessage();
        }

        $outArr = array("flag" => $flag, "msg" => $msg);
        echo jsonEncode($outArr);
    }

    /*
     * 
     */

    function doBatchCancelPaiche() {

        $flag = 0;
        $msg = "操作失败";

        try {
            $this->check->checkPower(array("power" => $this->projectSet["file"]["power_name"] . "_cancel_paiche", "ajax" => 1));

            $where = "";
            $is_sql = $this->input->getInt("is_sql", true);
            if ($is_sql == 1) {
                $searchParam = $this->_searchParam();
                $where = $searchParam["where"];
            } else {
                $cache_id_arr = $this->session->userdata($this->projectSet["file"]["cache_ids_name"]);
                if (empty($cache_id_arr)) {
                    throw new Exception("没有选择订单");
                }
                $ids = join(",", $cache_id_arr);
                $where = "where id in (" . $ids . ")";
            }
            $data = $this->order_model->getData($where, 1, 0, "");
            if (empty($data)) {
                throw new Exception("不存在订单");
            }
            if (count($data) > 1) {
                throw new Exception("一次只能取消派车一个订单");
            }
            $oldData = $data[0];
            $order = $data[0];
            $order_id = $data[0]["id"];

            if ($order["status_id"] != "pending_vehicle") {
                throw new Exception("订単只有在【已派车】状态才可取消");
            }

            $this->db->trans_start();

            $data = [
                "fieldArr" => [
                    "gongyingshang_custom_id" => 0,
                    "car_id" => 0,
                    "diaodu_user_id" => 0,
                    "cwjl_user_id" => 0,
                    "zhujia_driver_id" => 0,
                    "fujia_driver_id" => 0,
                    "pending_vehicle_at" => 0,
                    "status_id" => "created",
                    "updated_at" => time(),
                ],
                "whereArr" => [
                    "id" => $order_id,
                ],
            ];
            $this->order_model->updateData($data);

            //旧的车辆
            $exsit = $this->order_model->getData("where id<" . $order_id . " and car_id=" . $oldData["car_id"], 1, 1);
            if (!empty($exsit)) {
                //print_r($exsit);
                $this->order_model->updateData([
                    "fieldArr" => [
                        "is_huicheng" => 0,
                        "updated_at" => time(),
                    ],
                    "whereArr" => [
                        "id" => $exsit[0]["id"],
                    ],
                ]);
            }

            $flag = 1;
            $msg = "操作成功";

            $this->db->trans_complete();
        } catch (Exception $e) {
            $msg = $e->getMessage();
        }

        $outArr = array("flag" => $flag, "msg" => $msg);
        echo jsonEncode($outArr);
    }

    /*
     * 添加
     */

    function addSecondOrder() {

        try {
            $this->check->checkPower(array("power" => $this->projectSet["file"]["power_name"] . "_add"));

            $where = "";
            $is_sql = $this->input->getInt("is_sql", true);
            if ($is_sql == 1) {
                $searchParam = $this->_searchParam();
                $where = $searchParam["where"];
            } else {
                $cache_id_arr = $this->session->userdata($this->projectSet["file"]["cache_ids_name"]);
                if (empty($cache_id_arr)) {
                    throw new Exception("没有选择订单");
                }
                $ids = join(",", $cache_id_arr);
                $where = "where id in (" . $ids . ")";
            }
            $data = $this->order_model->getData($where, 1, 0, "");
            if (empty($data)) {
                throw new Exception("不存在订单");
            }
            if (count($data) > 1) {
                throw new Exception("只能选择1个订单二次运输");
            }
            $oldData = $data[0];

            if ($oldData["set_second_id"] > 0) {
                throw new Exception("该订单为二次运输订单，不可操作");
            }
            $data["oldData"] = $oldData;

            $order_id = $oldData["id"];

            $data["secondType"] = $this->order_model->secondType();

            $data["kehu"] = $this->custom_model->getData("where type_id=2 and status_id=1", 1, 0);

            #订单号
            $today = date("Ymd");
            $order = $this->order_model->getData("where second_order_id=" . $order_id . " order by set_second_id desc", 1, 1, "");
            if (!empty($order)) {
                $set_second_id = $order[0]["set_second_id"] + 1;
            } else {
                $set_second_id = 1;
            }
            $data["set_second_id"] = $set_second_id;

            $order_no = $oldData["order_no"] . "-" . str_pad($set_second_id, 2, 0, STR_PAD_LEFT);
            $data["order_no"] = $order_no;

            #提货地



            $data["doAddUrl"] = $this->projectSet["url"]["doAddSecondOrder"];

            $this->layout->view($this->projectSet["file"]["view"] . '/addSecondOrder', $data);
        } catch (Exception $e) {
            show_error($msg = $e->getMessage(), $e->getCode() ? $e->getCode() : 200, "系统提示");
        }
    }

    function doAddSecondOrder() {

        #权限

        $flag = 0;
        $msg = "操作失败";

        try {

            $this->check->checkPower(array("power" => $this->projectSet["file"]["power_name"] . "_add"));

            $needField = $this->order_model->needField();
            $fieldValue = $this->common->checkField($needField);

            $fieldValue["order_date"] = strtotime($fieldValue["order_date"]);

            $order_id = $this->input->postInt("order_id", true);
            if ($order_id <= 0) {
                throw new Exception("缺少原订单ID");
            }
            $oldData = $this->order_model->getDataById($order_id);
            if (empty($oldData)) {
                throw new Exception("原订单不存在");
            }

            $status = $this->order_model->status();
            if ($oldData["status_id"] != "created" && $oldData["status_id"] != "pending_vehicle") {
                throw new Exception("订単只有在【已制单】或【已派车】状态才可修改");
            }


            $second_type_id = $this->input->postInt("second_type_id", true);
            if ($second_type_id <= 0) {
                throw new Exception("请选择二次类型");
            }
            $set_second_id = $this->input->postInt("set_second_id", true);
            if ($set_second_id <= 0) {
                throw new Exception("缺少二次订单ID编号");
            }


            $this->db->trans_start();

            if ($fieldValue["org_id"] == -1) {
                if ($fieldValue["org_province_id"] <= 0) {
                    throw new Exception("请选择提货地州");
                }
                if ($fieldValue["org_city_id"] <= 0) {
                    //throw new Exception("请选择提货地城市");
                }
                if ($fieldValue["org_address"] == "") {
                    throw new Exception("请填上提货地具体地址");
                }
                $fieldValue["org_id"] = $this->custom_address_model->addData([
                    "custom_id" => $fieldValue["kehu_custom_id"],
                    "type_id" => 1,
                    "province_id" => $fieldValue["org_province_id"],
                    "city_id" => $fieldValue["org_city_id"],
                    "district_id" => $fieldValue["org_district_id"],
                    "address" => $fieldValue["org_address"],
                ]);
            } else {
                if ($fieldValue["org_id"] <= 0) {
                    throw new Exception("请选择提货地");
                }
                $org = $this->custom_address_model->getDataById($fieldValue["org_id"]);
                if (empty($org)) {
                    throw new Exception("选择的提货地不存在");
                }
                $fieldValue["org_province_id"] = $org["province_id"];
                $fieldValue["org_city_id"] = $org["city_id"];
                $fieldValue["org_district_id"] = $org["district_id"];
                $fieldValue["org_address"] = $org["address"];
            }

            if ($fieldValue["dest_id"] == -1) {
                if ($fieldValue["dest_province_id"] <= 0) {
                    throw new Exception("请选择送货地省份");
                }
                if ($fieldValue["dest_city_id"] <= 0) {
                    //throw new Exception("请选择送货地城市");
                }
                if ($fieldValue["dest_address"] == "") {
                    throw new Exception("请填上送货地具体地址");
                }
                $fieldValue["dest_id"] = $this->custom_address_model->addData([
                    "custom_id" => $fieldValue["kehu_custom_id"],
                    "type_id" => 2,
                    "province_id" => $fieldValue["dest_province_id"],
                    "city_id" => $fieldValue["dest_city_id"],
                    "district_id" => $fieldValue["dest_district_id"],
                    "address" => $fieldValue["dest_address"],
                ]);
            } else {
                if ($fieldValue["dest_id"] <= 0) {
                    throw new Exception("请选择送货地");
                }
                $dest = $this->custom_address_model->getDataById($fieldValue["dest_id"]);
                if (empty($dest)) {
                    throw new Exception("选择的送货地不存在");
                }
                $fieldValue["dest_province_id"] = $dest["province_id"];
                $fieldValue["dest_city_id"] = $dest["city_id"];
                $fieldValue["dest_district_id"] = $dest["district_id"];
                $fieldValue["dest_address"] = $dest["address"];
            }

            $uData = array_merge($fieldValue, [
                "set_second_id" => $set_second_id,
                "second_type_id" => $second_type_id,
                "second_order_id" => $order_id,
                "same_order_id" => $order_id,
                "status_id" => "created",
                "created_user_id" => $this->_adminInfo["id"],
                "created_at" => time(),
                "updated_at" => time(),
            ]);
            $insert_id = $this->order_model->addData($uData);

            $flag = 1;
            $msg = "操作成功";

            $this->db->trans_complete();
        } catch (Exception $e) {
            $msg = $e->getMessage();
        }

        $outArr = array("flag" => $flag, "msg" => $msg);
        echo jsonEncode($outArr);
    }

    public function updateIshuicheng() {

        $tmp = $this->base_model->getData("SELECT 
    t1.id,
    t1.car_id,
    CASE 
        WHEN EXISTS (
            SELECT 1 
            FROM order_main t2 
            WHERE t2.car_id = t1.car_id 
            AND t2.id > t1.id and t2.car_id>0
        ) THEN 1 
        ELSE 0 
    END AS is_car_id
FROM order_main t1
ORDER BY t1.id", 1, 0, "");

        foreach ($tmp as $k => $v) {
            $this->order_model->updateData([
                "fieldArr" => [
                    "is_huicheng" => $v["is_car_id"],
                ],
                "whereArr" => [
                    "id" => $v["id"],
                ],
            ]);
        }
    }

}
